package com.sanpu.kxe.business.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanpu.library.imagechoose.PhotoPicker;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragment;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.main.bean.CertificationOutput;
import com.sanpu.kxe.business.main.contract.AuthSecondStepContract;
import com.sanpu.kxe.business.main.interfaces.IOnSwitchPageListener;
import com.sanpu.kxe.business.main.presenter.AuthSecondStepPresenter;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.main.view.CertificateSecondActivity;
import com.sanpu.kxe.common.custom.SerializableHashMap;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.jump.eventbus.ReviewPhotoEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.roundview.RoundTextView;
import com.sanpu.kxe.module.specialunit.OnClickableSpanListener;
import com.sanpu.kxe.module.specialunit.SimplifySpanBuild;
import com.sanpu.kxe.module.specialunit.unit.SpecialClickableUnit;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：认证第二步
 * Created by 薛勇军 on 2018/7/17.
 */

public class AuthSecondStepFragment extends BaseFragment implements AuthSecondStepContract.View {

    @Bind(R.id.front)
    ImageView vFront;
    @Bind(R.id.front_image)
    ImageView vFrontImage;
    @Bind(R.id.front_image_cloud)
    TextView vFrontImageCloud;
    @Bind(R.id.reverse)
    ImageView vReverse;
    @Bind(R.id.reverse_image)
    ImageView vReverseImage;
    @Bind(R.id.reverse_image_cloud)
    TextView vReverseImageCloud;
    @Bind(R.id.commit)
    RoundTextView vCommit;
    @Bind(R.id.lastStepRtv)
    RoundTextView lastStepRtv;
    @Bind(R.id.idCardClaimTv)
    TextView idCardClaimTv;

    private AuthSecondStepContract.Presenter mPresenter;

    public IOnSwitchPageListener mOnSwitchPageListener;

    private CertificationOutput mOutput;

    private boolean isNeedUpload = true;

    private SerializableHashMap mSerializableHashMap;

    public void setOnSwitchPageListener(IOnSwitchPageListener mOnSwitchPageListener) {
        this.mOnSwitchPageListener = mOnSwitchPageListener;
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_auth_second;
    }

    @Override
    protected void initView() {
        super.initView();
        mPresenter = new AuthSecondStepPresenter(this);

        SpecialClickableUnit clickableUnit = new SpecialClickableUnit(new OnClickableSpanListener() {
            @Override
            public void onClick(TextView tv, String clickText) {
                mPresenter.openOldCertificateOneActivity();
            }
        });
        clickableUnit.setSpecialText("请点击使用人工审核");
        clickableUnit.setNormalTextColor(ContextCompat.getColor(getContext(), R.color.c_ff3f40));
        clickableUnit.setPressTextColor(ContextCompat.getColor(getContext(), R.color.c_ff3f40));
        clickableUnit.showUnderline();
        SimplifySpanBuild build = new SimplifySpanBuild(getContext(), idCardClaimTv, "4. 如照片一直未通过，");
        build.appendSpecialUnit(clickableUnit);
        idCardClaimTv.append(build.build());
    }

    @OnClick({R.id.commit, R.id.lastStepRtv, R.id.front, R.id.reverse})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.commit:
                if (vFrontImage.getTag() == null || vReverseImage.getTag() == null) {
                    ToastUtil.showTextViewPrompt("必须添加身份证正反面照片");
                    return;
                }
                if (!isNeedUpload && mOutput != null) {
                    showIdCardInfo(mOutput, mSerializableHashMap, isNeedUpload);
                } else {
                    mPresenter.uploadIdCardInfo();
                }
                break;
            case R.id.lastStepRtv:
                getActivity().finish();
                break;
            case R.id.front:
                if (vFrontImage.getTag() != null) {
                    mPresenter.takePhoto((String) vFrontImage.getTag(),
                            CommonConfig.REQUESTCODE_CERTIFICATE_VIEW_FRONT);
                } else {
                    MainOpenProvider.getInstance().openCertificateHelpActivity(
                            getContext(), CommonConfig.TYPE_IDFROPIC);
                }
                break;
            case R.id.reverse:
                if (vReverseImage.getTag() != null) {
                    mPresenter.takePhoto((String) vReverseImage.getTag(),
                            CommonConfig.REQUESTCODE_CERTIFICATE_VIEW_REVERSE);
                } else {
                    MainOpenProvider.getInstance().openCertificateHelpActivity(
                            getContext(), CommonConfig.TYPE_IDCONPIC);
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mOutput = ((CertificateSecondActivity) getActivity()).getCertificationOutput();
        mSerializableHashMap = ((CertificateSecondActivity) getActivity()).getSerializableHashMap();
    }

    @Override
    public void showIdCardInfo(CertificationOutput output, SerializableHashMap hashMap, boolean isNeedUpload) {
        if (mOutput == null)
            mOutput = new CertificationOutput();
        mOutput.setIdCardName(output.getIdCardName());
        mOutput.setIdCardNo(output.getIdCardNo());
        mOutput.setIdCardAddress(output.getIdCardAddress());
        mOutput.setIdFroPicPath(output.getIdFroPicPath());
        mOutput.setIdConPicPath(output.getIdConPicPath());
        this.isNeedUpload = isNeedUpload;
        this.mSerializableHashMap = hashMap;
        if (mOutput != null) {
            String message = "姓名：" + output.getIdCardName();
            String remark = "身份证号：" + output.getIdCardNo();
            DialogUtil.getInstance().showDialogTwoBtnVertical(getContext(),
                    "当前上传的身份证信息", message, remark, "确认无误", "信息错误，重拍", new DialogViewListener() {
                        @Override
                        public void btnRightConfirm() {
                            ((CertificateSecondActivity) getActivity()).setCertificationOutput(mOutput);
                            ((CertificateSecondActivity) getActivity()).setSerializableHashMap(mSerializableHashMap);
                            mOnSwitchPageListener.onSwitchPage();
                        }

                        @Override
                        public void btnLeftCancel() {

                        }
                    });
        }
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            ArrayList<String> photos =
                    data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            switch (requestCode) {
                case CommonConfig.REQUESTCODE_CERTIFICATE_VIEW_FRONT:
                    if (photos == null || photos.size() == 0) {
                        vFrontImage.setTag(null);
                        vFrontImage.setImageDrawable(null);
                        vFrontImage.setVisibility(View.GONE);
                        vFrontImageCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_IDFROPIC);
                        isNeedUpload = true;
                    }
                    break;
                case CommonConfig.REQUESTCODE_CERTIFICATE_VIEW_REVERSE:
                    if (photos == null || photos.size() == 0) {
                        vReverseImage.setTag(null);
                        vReverseImage.setImageDrawable(null);
                        vReverseImage.setVisibility(View.GONE);
                        vReverseImageCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_IDCONPIC);
                        isNeedUpload = true;
                    }
                    break;
            }
        }
    }

    @Override
    public void refreshView(ReviewPhotoEvent event) {
        String filePath = event.getFilePath();
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        isNeedUpload = true;
        String fileIdName;
        switch (event.getCurrentType()) {
            case CommonConfig.TYPE_IDFROPIC:
                fileIdName = CommonConfig.TYPE_IDFROPIC;
                JKImageLoader.getInstance().displayImage(getContext(), "file://" + filePath, vFrontImage);
                vFrontImage.setTag(filePath);
                vFrontImage.setVisibility(View.VISIBLE);
                vFrontImageCloud.setVisibility(View.VISIBLE);
                break;
            case CommonConfig.TYPE_IDCONPIC:
                fileIdName = CommonConfig.TYPE_IDCONPIC;
                JKImageLoader.getInstance().displayImage(getContext(), "file://" + filePath, vReverseImage);
                vReverseImage.setTag(filePath);
                vReverseImage.setVisibility(View.VISIBLE);
                vReverseImageCloud.setVisibility(View.VISIBLE);
                break;
            default:
                return;
        }
        mPresenter.onCompress(filePath, fileIdName);
    }

    @Override
    public void showLoadingDialog(boolean cancelable, String content) {
        ((BaseTitleActivity) getActivity()).showLoadingDialog(cancelable, content);
    }

    @Override
    public void showErrorText(Throwable e) {
        ((BaseTitleActivity) getActivity()).showErrorText(e);
    }

    @Override
    public void dismissLoadingDialog() {
        ((BaseTitleActivity) getActivity()).dismissLoadingDialog();
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    public void setPresenter(AuthSecondStepContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
